package test

import (
	"aigen-todo/internal/api"
	"aigen-todo/internal/config"
	"aigen-todo/internal/repository"
	"aigen-todo/internal/service"
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

// TestRegisterAPI 测试用户注册API
func TestRegisterAPI(t *testing.T) {
	// 创建内存仓库和服务（不依赖真实数据库）
	userRepo := repository.NewUserRepository(nil) // 传入nil，因为我们将在服务层模拟行为
	userService := service.NewUserService(userRepo)

	// 设置Gin路由器
	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.POST("/api/v1/register", api.RegisterHandler(userService))

	// 测试用例1: 参数验证失败
	t.Run("ValidationFailed", func(t *testing.T) {
		// 准备无效的请求数据
		registerReq := map[string]interface{}{
			"username": "testuser",
			// 缺少必需的email和password字段
		}
		jsonData, _ := json.Marshal(registerReq)

		// 创建HTTP请求
		req, _ := http.NewRequest("POST", "/api/v1/register", bytes.NewBuffer(jsonData))
		req.Header.Set("Content-Type", "application/json")

		// 创建响应记录器
		w := httptest.NewRecorder()

		// 执行请求
		router.ServeHTTP(w, req)

		// 验证响应
		assert.Equal(t, http.StatusBadRequest, w.Code)

		// 解析响应数据
		var response map[string]interface{}
		json.Unmarshal(w.Body.Bytes(), &response)

		assert.Equal(t, float64(10001), response["code"])
		assert.Equal(t, false, response["success"])
		assert.Equal(t, "参数错误", response["message"])
	})
}

// TestLoginAPI 测试用户登录API
func TestLoginAPI(t *testing.T) {
	// 创建内存仓库和服务（不依赖真实数据库）
	userRepo := repository.NewUserRepository(nil) // 传入nil，因为我们将在服务层模拟行为
	userService := service.NewUserService(userRepo)

	// 创建配置
	cfg := &config.Config{
		JWT: config.JWTConfig{
			Secret:     "test_secret",
			Expiration: 24,
		},
	}

	// 设置Gin路由器
	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.POST("/api/v1/login", api.LoginHandler(userService, cfg))

	// 测试用例1: 参数验证失败
	t.Run("ValidationFailed", func(t *testing.T) {
		// 准备无效的登录请求数据
		loginReq := map[string]interface{}{
			"username": "testuser",
			// 缺少必需的password字段
		}
		jsonData, _ := json.Marshal(loginReq)

		// 创建HTTP请求
		req, _ := http.NewRequest("POST", "/api/v1/login", bytes.NewBuffer(jsonData))
		req.Header.Set("Content-Type", "application/json")

		// 创建响应记录器
		w := httptest.NewRecorder()

		// 执行请求
		router.ServeHTTP(w, req)

		// 验证响应
		assert.Equal(t, http.StatusBadRequest, w.Code)

		// 解析响应数据
		var response map[string]interface{}
		json.Unmarshal(w.Body.Bytes(), &response)

		assert.Equal(t, float64(10001), response["code"])
		assert.Equal(t, false, response["success"])
		assert.Equal(t, "参数错误", response["message"])
	})
}
